<template>
  <div class="wang-editor-container">
    <!-- 工具栏 -->
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      class="editor-toolbar"
    />
    
    <!-- 编辑器 -->
    <Editor
      v-model="editorHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
      class="editor-content"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, watch, onBeforeUnmount } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import type { IDomEditor, IEditorConfig } from '@wangeditor/editor'

const props = defineProps({
  // 实现 v-model 绑定
  modelValue: {
    type: String,
    default: ''
  },
  // 编辑器配置
  editorConfig: {
    type: Object as () => Partial<IEditorConfig>,
    default: () => ({})
  },
  // 工具栏配置
  toolbarConfig: {
    type: Object,
    default: () => ({})
  },
  // 编辑器模式：default 或 simple
  mode: {
    type: String,
    default: 'default'
  },
  // 占位文本
  placeholder: {
    type: String,
    default: '请输入内容...'
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

// 编辑器实例（必须使用 shallowRef）
const editorRef = shallowRef<IDomEditor | null>(null)

// 编辑器内容（使用 v-model 绑定）
const editorHtml = ref(props.modelValue)

// 合并配置
const mergedEditorConfig = ref<Partial<IEditorConfig>>({
  placeholder: props.placeholder,
  readOnly: false,
  autoFocus: false,
  scroll: true,
  ...props.editorConfig
})

// 创建编辑器回调
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}

// 内容变化回调
const handleChange = (editor: IDomEditor) => {
  const html = editor.getHtml()
  emit('update:modelValue', html)
  emit('change', html)
}

// 监听外部 modelValue 变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== editorHtml.value && editorRef.value) {
    editorHtml.value = newValue
  }
})

// 组件卸载时销毁编辑器
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy()
    editorRef.value = null
  }
})

// 暴露编辑器实例
defineExpose({
  getEditor: () => editorRef.value,
  getHtml: () => editorHtml.value,
  getText: () => editorRef.value?.getText() || ''
})
</script>

<style scoped>
.wang-editor-container {
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  border-bottom: 1px solid #ccc;
}

.editor-content {
  height:400px !important;
  overflow-y: auto;
}
</style>